/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/// <reference path="../base/lcc.ts" />
/// <reference path="../utils/js.ts" />
/// <reference path="../log/log-manager.ts" />

namespace lcc {

const Path = require('path');
const Fs = require('fs');

const TAG = "lcc/table/table-manager.ts";

/**
 * @zh
 * 数据表文件的默认路径
 */
export let TABLE_PATH = Path.join(__dirname, 'tables');

/**
 * @zh
 * 数据表对象映射表<br/>
 * 在加载完对应数据表后，可以直接通过这个变量访问数据表对象<br/>
 * ```
 *      lcc.tableMgr.loadTable('test');
 *      let testTable = TABLES.test;
 *      // let testTable = TABLES['test'];
 * ```
 */
export let TABLES:{[key:string]:any} = js.createMap();

/**
 * @zh
 * 数据表管理器<br/>
 * 主要用于管理游戏数据表，这些表一般由策划配置<br/>
 * 数据表的加载与合并功能
 */
class TableManager {
	
    /**
     * 获得所有表
     */
    public getTables(){
        return TABLES;
    }
    
    /**
     * 获得指定表
     * @param tname 
     */
    public getTable<T = any>(tname:string){
        return <T>(TABLES[tname]);
    }

	/**
	 * @zh
	 * 移除所有数据表
	 * 
	 * @param tname - 表名称
	 */
    public removeTable(tname:string){
		delete TABLES[tname];
	}
    
	/**
     * @zh
	 * 移除所有数据表
	 */
	public removeAllTables(){
		for(let tbname of Object.keys(TABLES)){
			delete TABLES[tbname];
		}
    }

    /**
     * @zh
     * 加载数据表文件
     * 
     * @param tfile - 数据表文件，当前只支持json
     */
    public loadTableFile(tfile:string){
        if(Fs.existsSync(tfile)){
            if(tfile.endsWith('.json')){
                let table = JSON.parse(Fs.readFileSync(tfile));
                js.mergeMap(TABLES, table, { tag : TAG, source : tfile });
                DEBUG.TABLE && logMgr.debug(TAG, `load table ${JSON.stringify(table)} from ${tfile}`);
            }else{
                logMgr.error(TAG, `loadTableFile ${tfile} format not support!!!`);
            }
        }else{
            logMgr.error(TAG, `loadTableFile ${tfile} not found!!!`);
        }
    }

    /**
     * @zh
     * 根据默认路径加载数据表<br/>
     * 默认加载路径为[TABLE_PATH]</br>
     * 
     * @param tnames - 数据表名称列表。不要文件后缀
     */
    public loadTable(...tnames:string[]){
        for(let tname of tnames){
            this.loadTableFile(Path.join(TABLE_PATH, `${tname}.json`));
        }
    }
};

/**
 * @zh
 * 数据表管理器对象
 */
export const tableMgr = new TableManager();

}
